<template>
	<gui-page :customHeader="true" :isHeaderSized="false" ref="guiPage">
		<!-- 自定义头部导航 -->
		<template v-slot:gHeader>
			<view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
				<!-- 返回按钮 -->
				<gui-header-leading :backButtonClass="['gui-color-white']" :home="false"
					:back="false"></gui-header-leading>
				<!-- 导航文本此处也可以是其他自定义内容 -->

				<view style="width:60rpx;"></view>
			</view>
		</template>
		<!-- 页面主体 -->
		<template v-slot:gBody>
			<view>
				<view class="system-container">
					<view class="info">
						<view class="system-empty">
						</view>
						<view class="system-info">

							<view class="system-avatar">
								<image src="@/static/assets/005.png" style="width:128rpx;border-radius: 50%;"
									mode="widthFix">
								</image>
								<view class="system-user_name">
									<view class="nickname">
										<text style="margin:0 12rpx;">{{userForm.name}}</text>
										<u-tag :text="r['name']" size="mini" type="warning" v-for="(r,ind) in roles"
											:key="ind"></u-tag>
									</view>
									<text class="declaration">欢迎使用汽车报修系统</text>
								</view>
							</view>
						</view>
						<view class="system-achievement">
							<view class="box">
								<view class="running icon-top-raning"
									style="font-size: 48rpx;font-weight:600;color:#f5d498;">

								</view>
								<text class="title">{{info.distanceDay}}</text>
								<view class="subtitle">
									<text>正常运行</text>
									<text class="hulu-font-5">（天）</text>
								</view>
							</view>
							<view class="box">
								<view class="running icon-gongyinglianfuwu" style="font-size: 48rpx;color:#f5d498;">

								</view>
								<text class="title">{{info.totalRepairCount}}</text>
								<view class="subtitle">
									<text>累计</text>
									<text class="hulu-font-5">（次）</text>
								</view>
							</view>
							<view class="box">
								<view class="running icon-good-fill" style="font-size: 48rpx;color:#f5d498;">

								</view>
								<text class="title">{{info.repairCount}}</text>
								<view class="subtitle">
									<text>本年</text>
									<text class="hulu-font-5">（次）</text>
								</view>
							</view>
							<view class="box">
								<button @tap="toHistory" type="default"
									style="width:120rpx;height:80rpx; border-radius:80rpx;"
									class="gui-button gui-button-mini gui-bg-orange1 gui-noborder">
									<text class="gui-color-white gui-button-text  gui-button-text-mini">历史工单</text>
								</button>
							</view>

						</view>
					</view>
				</view>
				<view class="" style="height:88rpx;">

				</view>
				<gui-car-number ref="guiCarNumber1" @confirm="confirm1"></gui-car-number>

				<up-action-sheet mode="center" :show="state.showFault" :actions="state.faults" title="请选择故障类型"
					description="请如实填写" @close="state.showFault = false" @select="faultSelect">
				</up-action-sheet>

				<gui-car-number ref="guiCarNumber2" @confirm="confirm2"></gui-car-number>

				<up-action-sheet mode="center" :show="state.showFault" :actions="state.faults" title="请选择故障类型"
					description="请如实填写" @close="state.showFault = false" @select="faultSelect">
				</up-action-sheet>
				<swiper :style="{height:`${mainHeight}rpx`}" :current="currentIndex" @change="swiperChange">
					<!-- 轮播项目数量对应 上面的选项标签 -->

					<swiper-item>
						<scroll-view :style="{height:mainHeight+'px'}" :scroll-y="true">
							<view class="gui-bg-white gui-padding gui-relative" style="border-radius: 12rpx;">
								<view class="gui-absolute-rt">
									<image src="../../static/assets/4.png" mode="widthFix" style="width:240rpx;">
									</image>
								</view>
								<view class="gui-padding-x" style="z-index:1;">
									<view class="hulu-font-2 gui-text-center" style="font-weight: bold;">
										正常报修
									</view>

									<up-form labelPosition="left" :model="state.model" :rules="state.rules"
										ref="formRef1" style="z-index:1;">
										<up-form-item label="姓名" prop="repairState.user_name" borderBottom>
											<up-input v-model="state.model.repairState.user_name"
												border="none"></up-input>
										</up-form-item>
										<up-form-item label="电话" prop="repairState.phone" borderBottom>
											<up-input v-model="state.model.repairState.phone" border="none"></up-input>
										</up-form-item>
										<up-form-item label="故障" prop="repairState.repair_type_id" borderBottom
											@click="state.showFault = true; hideKeyboard()">
											<view class="gui-flex gui-justify-content-start gui-align-items-center">
												<text>{{state.model.repairState.repair_type_name}}</text>
												<up-input v-model="state.model.repairState.repair_type_id" disabled
													disabledColor="#ffffff" placeholder="请选择故障"
													border="none"></up-input>
											</view>
											<template #right>
												<up-icon name="arrow-right"></up-icon>
											</template>
										</up-form-item>
										<up-form-item label="车牌" prop="repairState.license" borderBottom
											@click="showLicense1">
											<up-input v-model="state.model.repairState.license" disabled
												disabledColor="#ffffff" placeholder="请选择车牌" border="none"></up-input>
											<template #right>
												<up-icon name="arrow-right"></up-icon>
											</template>
										</up-form-item>
										<up-form-item label="问题" prop="repairState.description" borderBottom>
											<up-textarea v-model="state.model.repairState.description" count
												placeholder="请描述问题"></up-textarea>
										</up-form-item>
										<up-form-item label="图片" prop="repairState.images" borderBottom>
											<up-upload :fileList="fileList" @afterRead="afterRead" name="1"
												@clickPreview="clickPreview" multiple :maxCount="3"></up-upload>
										</up-form-item>
										<view class="gui-margin-top">
											<button type="default" style="border-radius:80rpx;" @tap="onSubmit"
												class="gui-button  gui-bg-orange1 gui-noborder">
												<text class="gui-color-white gui-button-text">立即报修</text>
											</button>
										</view>
									</up-form>

								</view>
							</view>
						</scroll-view>
					</swiper-item>

					<swiper-item>
						<scroll-view :style="{height:mainHeight+'px'}" :scroll-y="true" class="scroll-view"
							ref="scrollViewRef">
							<view class="gui-bg-white gui-padding gui-relative" style="border-radius: 12rpx;">
								<view class="gui-absolute-rt">
									<image src="../../static/assets/5.png" mode="widthFix" style="width:240rpx;">
									</image>
								</view>
								<view class="gui-padding-x" style="z-index:1;">
									<view class="hulu-font-2 gui-text-center" style="font-weight: bold;">
										应急报修
									</view>

									<up-form labelPosition="left" :model="state.model" :rules="state.rules"
										ref="formRef2" style="z-index:1;">
										<up-form-item label="姓名" prop="repairState.user_name" borderBottom>
											<up-input v-model="state.model.repairState.user_name"
												border="none"></up-input>
										</up-form-item>
										<up-form-item label="电话" prop="repairState.phone" borderBottom>
											<up-input v-model="state.model.repairState.phone" border="none"></up-input>
										</up-form-item>
										<up-form-item label="位置" prop="repairState.coordinates" borderBottom>
											<up-button @click="getAddr" type="primary" color="white" size="small"
												:hairline="false" class="gui-noborder gui-block gui-ellipsis"
												style="border: none;width:100rpx;">
												<up-icon name="map-fill" color="#FF6E40" size="24"></up-icon>
												<text class="hulu-btn-text-color">获取</text>
												<view class="hulu-text-color5">{{state.model.repairState.address}}
												</view>
											</up-button>
										</up-form-item>
										<up-form-item label="故障" prop="repairState.repair_type_id" borderBottom
											@click="state.showFault = true; hideKeyboard()">
											<view class="gui-flex gui-justify-content-start gui-align-items-center">
												<text>{{state.model.repairState.repair_type_name}}</text>
												<up-input v-model="state.model.repairState.repair_type_id" disabled
													disabledColor="#ffffff" placeholder="请选择故障"
													border="none"></up-input>
											</view>
											<template #right>
												<up-icon name="arrow-right"></up-icon>
											</template>
										</up-form-item>
										<up-form-item label="车牌" prop="repairState.license" borderBottom
											@click="showLicense2">
											<up-input v-model="state.model.repairState.license" disabled
												disabledColor="#ffffff" placeholder="请选择车牌" border="none"></up-input>
											<template #right>
												<up-icon name="arrow-right"></up-icon>
											</template>
										</up-form-item>
										<up-form-item label="问题" prop="repairState.description" borderBottom>
											<up-textarea v-model="state.model.repairState.description" count
												placeholder="请描述问题"></up-textarea>
										</up-form-item>
										<up-form-item label="图片" prop="repairState.images" borderBottom>
											<up-upload :fileList="fileList" @afterRead="afterRead" name="1" :deletable="true"
												@delete="deletePicture" @clickPreview="clickPreview" multiple
												:maxCount="3"></up-upload>
										</up-form-item>
										<view class="gui-margin-top">
											<button type="default" style="border-radius:80rpx;" @tap="onSubmit"
												class="gui-button  gui-bg-orange1 gui-noborder">
												<text class="gui-color-white gui-button-text">立即报修</text>
											</button>
										</view>
									</up-form>

								</view>
							</view>
						</scroll-view>
					</swiper-item>

				</swiper>

			</view>
		</template>
	</gui-page>
</template>

<script lang="ts">
	import graceJS from '@/Grace6/js/grace.js';
	import useRepair from "@/api/repair"
	import useRepairType from '@/api/repair_type'
	const { getRepairType } = useRepairType()
	const { storeRepair, getRepairInfo } = useRepair()
	export default {
		data() {
			return {
				currentIndex: 0,
				mainHeight: 1300,
				info: {
					distanceDay: 0,
					repairCount: 0,
					totalRepairCount: 0,
				},
				state: {
					showLicense1: false,
					showLicense2: false,
					showFault: false,
					model: {
						repairState: {
							user_name: '',
							license: '',
							phone: '',
							way: 1,
							coordinates: {
								type: "Point",
								coordinates: [null, null]
							},
							repair_type_id: null,
							repair_type_name: "",
							address: "",
							description: "",
							images: []
						},
					},
					faults: [
					],
					rules: {
						'repairState.user_name': {
							type: 'string',
							required: true,
							message: '请填写姓名',
							trigger: ['blur', 'change'],
						},
						'repairState.phone': [{
							type: 'string',
							required: true,
							message: '请输入手机号',
							trigger: ['blur', 'change'],
						}, {
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}],
						'repairState.license': {
							type: 'string',
							required: true,
							message: '请输入车牌',
							trigger: ['blur', 'change'],
						},
						'repairState.repair_type_id': {
							type: 'number',
							required: true,
							message: '请选择故障',
							trigger: ['blur', 'change'],
						},
						'repairState.description': {
							type: 'string',
							required: true,
							message: '请简单描述',
							trigger: ['blur', 'change'],
						},
					},
				},
				userForm: uni.getStorageSync("user") ? JSON.parse(uni.getStorageSync("user")) : {},
				roles: uni.getStorageSync("roles") ? JSON.parse(uni.getStorageSync("roles")) : [],
				fileList: [],
			}
		},

		async created() {
			let { data } = await getRepairType()
			let info = await getRepairInfo()
			this.info.distanceDay = info.data.distanceDay
			this.info.repairCount = info.data.repairCount
			this.info.totalRepairCount = info.data.totalRepairCount
			this.state.faults = data.map(item => {
				return {
					name: item.name,
					id: item.id
				}
			})
		},
		onReady: function () {
			// 设置默认值
			setTimeout(() => {
				// 默认新能源
				this.$refs.guiCarNumber1.setType(0);
				this.$refs.guiCarNumber2.setType(0);
			}, 1000);
		},
		mounted() {
			graceJS.getRefs('guiPage', this, 0, (ref) => {
				// 获取到 ref
				ref.pageLoadingOpen();
				setTimeout(() => {
					ref.pageLoadingClose();
				}, 1300);
			});
		},
		methods: {
			deletePicture(event) {
				console.log(this.fileList)
				this.fileList.splice(event.index, 1);
			},
			swiperChange(e) {
				this.currentIndex = e.detail.current
				this.resetForm()
				if (this.currentIndex == 0) {
					this.mainHeight = 1300
					this.state.model.repairState.way = 1
				} else {
					this.mainHeight = 1300
					this.state.model.repairState.way = 2
					//调用滚动
					this.scrollToBottom()
				}
			},
			resetForm() {
				this.state.model.repairState = {
					name: '',
					license: '',
					mobile: '',
					coordinates: {
						type: "Point",
						coordinates: [null, null]
					},
					repair_type_id: null,
					repair_type_name: "",
					address: "",
					description: "",
					images: []
				}
			},
			scrollToBottom() {
				// console.log(this.$refs)
				// uni.createSelectorQuery().in(this).select('.scroll-view').boundingClientRect((rect) => {
				// 	if (!rect) return;
				// 	const scrollViewHeight = rect.height;
				// 	const contentTotalHeight = this.mainHeight + 100; // 假设每行内容高度为20px，可根据实际情况调整
				// 	this.$refs.scrollViewRef.scrollTop = contentTotalHeight - scrollViewHeight;
				// }).exec();
			},
			toHistory() {
				uni.navigateTo({
					url: `/subpage/user/history`
				})
			},
			confirm1(val) {
				this.state.model.repairState.license = val;
			},
			confirm2(val) {
				this.state.model.repairState.license = val;
			},
			hideKeyboard() {

			},
			faultSelect(e) {
				this.state.model.repairState.repair_type_id = e.id;
				this.state.model.repairState.repair_type_name = e.name;
			},
			showLicense1() {
				this.$refs.guiCarNumber1.open()
			},
			showLicense2() {
				this.$refs.guiCarNumber2.open()
			},
			getAddr() {
				uni.chooseLocation({
					success: (res) => {
						let newLoc = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						this.state.model.repairState.address = res.address
						this.state.model.repairState.coordinates = {
							type: "Point",
							coordinates: [newLoc.longitude, newLoc.latitude]
						}
					},
					fail: () => {
						console.log('用户拒绝或操作失败');
					}
				});
			},
			clickPreview(url, lists, name) {
				console.log(url, lists, name)
			},
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileList.length;
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中',
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this.fileList[fileListLen];
					this.fileList.splice(fileListLen, 1, {
						...item,
						status: 'success',
						message: '',
						url: result,
					});
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				const token = uni.getStorageSync("token")
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${uni.$host}/api/mini/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						header: {
							Authorization: `Bearer ${token}`
						},
						name: 'file',
						formData: {
							user: 'test',
						},
						success: (res) => {
							this.state.model.repairState.images.push(`${uni.$host}/upload/${JSON.parse(res.data)['data']}`)
							resolve(`${uni.$host}/upload/${JSON.parse(res.data)['data']}`);
						},
					});
				})
			},
			onSubmit() {
				console.log(this.state.model.repairState)
				if (this.currentIndex == 0) {
					this.$refs.formRef1.validate().then(async valid => {
						if (valid) {
							uni.$u.toast('校验通过')

							await storeRepair(this.state.model.repairState)
							this.$refs.formRef2.resetFields()
							this.fileList = []
						} else {
							uni.$u.toast('校验失败')
						}
					}).catch(() => {
						// 处理验证错误  
						uni.$u.toast('校验失败')
					});
				} else {
					this.$refs.formRef2.validate().then(async valid => {
						if (valid) {
							uni.$u.toast('校验通过')
							console.log(this.state.model.repairState)
							await storeRepair(this.state.model.repairState)
							this.$refs.formRef2.resetFields()
							this.fileList = []
						} else {
							uni.$u.toast('校验失败')
						}
					}).catch(() => {
						// 处理验证错误  
						uni.$u.toast('校验失败')
					});
				}

			},
		}
	}
</script>

<style lang="scss">
	.system-container {
		height: 100%;

		.info {
			color: white;
			background-color: #0672EC;
			height: 400rpx;
			position: relative;

			.system-empty {
				height: 100rpx;
				font-size: 28rpx;
				color: white;
			}



			.system-info {
				height: 180rpx;
				display: flex;
				margin: 0 30rpx 0 30rpx;

				.system-avatar {
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.system-user_name {
						margin-left: 30rpx;
						display: flex;
						flex-direction: column;

						.nickname {
							color: white;
							display: flex;
						}

						.declaration {
							font-size: 28rpx;
							color: white;
						}
					}
				}


			}

			.system-achievement {
				width: 700rpx;
				height: 100rpx;
				margin: 0 30rpx;
				margin-top: 30rpx;
				display: flex;
				justify-content: space-around;
				align-items: center;
				border-radius: 100rpx;
				padding: 30rpx 0;
				background-image: linear-gradient(180deg, rgba(255, 255, 255, 0) -30%, rgba(255, 255, 255, 0) 50%);
				box-shadow: 0px 2px 37px rgba(0, 0, 0, 0.3);
				backdrop-filter: blur(25px);

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					font-size: 36rpx;
					font-weight: 500;

					.subtitle {
						display: flex;
						// flex-direction: column;
						align-items: center;
						font-size: 24rpx;
						color: #FF6E40;
						font-weight: bold;
					}
				}
			}
		}
	}
</style>